import 'package:eco_report_snap/services/database_service.dart';
import 'package:get/get.dart';

enum ComplaintType { air, water, soil }

class Complaint {
  final int? id;
  final String phone;
  final ComplaintType type;
  final String description;
  final String? imagePath;
  final String? videoPath;
  final double latitude;
  final double longitude;
  final String address;
  final DateTime createdAt;
  final String? adminResponse;
  final bool isProcessed;

  Complaint({
    this.id,
    required this.phone,
    required this.type,
    required this.description,
    this.imagePath,
    this.videoPath,
    required this.latitude,
    required this.longitude,
    required this.address,
    required this.createdAt,
    this.adminResponse,
    this.isProcessed = false,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'phone': phone,
      'type': type.toString().split('.').last,
      'description': description,
      'imagePath': imagePath,
      'videoPath': videoPath,
      'latitude': latitude,
      'longitude': longitude,
      'address': address,
      'createdAt': createdAt.toIso8601String(),
      'adminResponse': adminResponse,
      'isProcessed': isProcessed ? 1 : 0,
    };
  }

  factory Complaint.fromMap(Map<String, dynamic> map) {
    return Complaint(
      id: map['id'],
      phone: map['phone'],
      type: ComplaintType.values.firstWhere(
        (e) => e.toString().split('.').last == map['type'],
      ),
      description: map['description'],
      imagePath: map['imagePath'],
      videoPath: map['videoPath'],
      latitude: map['latitude'],
      longitude: map['longitude'],
      address: map['address'],
      createdAt: DateTime.parse(map['createdAt']),
      adminResponse: map['adminResponse'],
      isProcessed: map['isProcessed'] == 1,
    );
  }
}

class ComplaintController extends GetxController {
  final RxList<Complaint> complaints = <Complaint>[].obs;
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    loadComplaints();
  }

  Future<void> loadComplaints() async {
    isLoading.value = true;
    final db = DatabaseService();
    final list = await db.getAllComplaints();
    complaints.value = list;
    isLoading.value = false;
  }

  void updateComplaint(Complaint complaint) {
    final index = complaints.indexWhere((c) => c.id == complaint.id);
    if (index != -1) {
      complaints[index] = complaint;
    }
  }

  void deleteComplaint(int id) {
    complaints.removeWhere((c) => c.id == id);
  }
}
